import { createRouter, createWebHistory } from 'vue-router'
import { useUserStore, useAuthStore } from '@/stores'
import { staticRotes, notFoundRoute } from './staticRotes'
import { adminDynamicRotes } from "./rotes/adminDynamicRotes"
import { getUserInfo } from '@/api/login'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: staticRotes
})

router.beforeEach(async (to) => {
  window.document.title = to.name
  const userStore = useUserStore()
  // console.log('to:', to)

  if (to.path == '/login') {
    return true
  }
  if (!userStore.token && to.path != '/login') {
    console.log('不含token')
    return '/login'
  }
  const authStore = useAuthStore()
  // console.log(authStore.authComponentList)
  if (!authStore.authComponentList.length) {
    console.log('运行initDyanamicRouter')
    await initDynamicRouter()
    return true
  }

  if (to.matched.length === 0) {
    // console.log('matched为空')
    await initDynamicRouter()
    router.push(to.path)
  }
  return true

})

export default router

const initDynamicRouter = async () => {
  const authStore = useAuthStore()
  const userStore = useUserStore()
  try {

    await getUserInfo().then((res) => {
      if (res.data.success) {
        userStore.setUserInfo(res.data.data)
        authStore.setauthComponentList(res.data.data.components)
        authStore.setauthPermissionList(res.data.data.permissions)
      }
    }
    )
    // 1.请求用户信息，携带路由权限信息
    // await userStore.GetInfoAction()

    // 判断当前用户有没有菜单权限
    // if (!authStore.authRouterList.length) {
    //   ElNotification({
    //     title: '无权限访问',
    //     message: '当前账号无任何菜单权限，请联系系统管理员！',
    //     type: 'warning',
    //     duration: 3000,
    //   })
    //   RESEETSTORE()
    //   router.replace(LOGIN_URL)
    //   return Promise.reject('No permission')
    // }

    // 2.过滤路由
    const routerList = filterAsyncRoutes(
      adminDynamicRotes,
      authStore.authComponentList,
    )

    // 3.添加动态路由
    routerList.forEach((route) => {
      // console.log(route)
      router.addRoute(route)
    })

    // 4.添加notFound路由
    router.addRoute(notFoundRoute)
    // console.log('routerList', routerList)
    // 5.处理subMenu数据,静态路由和动态路由拼接，过滤isHide=true的路由
    const menuList = getMenuList([
      ...staticRotes,
      ...routerList,
    ])
    authStore.setauthMenuList(menuList)
  } catch (error) {
    // 当按钮 || 菜单请求出错时，重定向到登陆页
    router.replace('/login')
    return Promise.reject(error)
  }
}

function filterAsyncRoutes(
  dynamicRoutes,
  authComponentList
) {
  return dynamicRoutes.filter((route) => {
    // 1.如果authComponentList中不包含dynamRotues的路径，则过滤掉
    if (!authComponentList.includes(route.path)) {
      return false
    }

    // 2.如果当前route还有子路由(也就是有children), 需要对子路由也进行权限过滤
    if (route.children && route.children.length > 0) {
      route.children = filterAsyncRoutes(route.children, authComponentList)
    }
    return true
  })
}

function getMenuList(menuList) {
  const newMenuList = JSON.parse(JSON.stringify(menuList))

  return newMenuList.filter((item) => {
    item.children?.length && (item.children = getMenuList(item.children))
    return !item.meta?.isHide
  })
}


